import React, { useMemo } from "react";
import { Button, Dropdown, Space, type MenuProps } from "antd"
import { SettingOutlined, PrinterOutlined, UploadOutlined, DownOutlined } from '@ant-design/icons';
import styles from "./index.module.less"
import type { ToolBarOptions } from "../types"
import { useTableContext } from "../context";
import Setting from "./Setting";

type Props = {
  options: ToolBarOptions
}

const defaultOption = {
  show: true,
  onClick: () => { }
}

// 使用React.memo包装组件，避免不必要的重渲染
const ToolBar = React.memo((props: Props) => {
  const tableData = useTableContext();
  const { setting = {show:true}, print = defaultOption, batch = {}, outPut = defaultOption } = props.options

  // 使用useMemo缓存下拉菜单项，避免不必要的重新生成
  const items: MenuProps['items'] = useMemo(() => {
    return batch.dropDownOptions?.map(item => ({
      label: item.label,
      key: item.key,
      icon: item.icon
    }))
  }, [batch.dropDownOptions])

  const menuProps: MenuProps = {
    items,
    onClick: (value) => {
      batch.onClick && batch.onClick(tableData.selectRows, value.key)
    },
  };

  return (
    <div className={styles.wrapper}>
      <Space>
        {
          print.show && <Button onClick={print.onClick} icon={<PrinterOutlined />}>
            打印
          </Button>
        }

        {
          outPut.show && <Button onClick={outPut.onClick} icon={<UploadOutlined />}>
            导出
          </Button>
        }

        {batch && batch.dropDownOptions && batch.dropDownOptions.length > 0 && (
          <Dropdown menu={menuProps}>
            <Button>
              <Space>
                批量操作
                <DownOutlined />
              </Space>
            </Button>
          </Dropdown>
        )}
        <Setting show={!!setting.show}></Setting>
      </Space>
    </div>
  )
});

export default ToolBar;